package com.wjb.xietong.W3;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.wjb.xietong.Volley.AuthFailureError;
import com.wjb.xietong.Volley.NetworkResponse;
import com.wjb.xietong.Volley.ParseError;
import com.wjb.xietong.Volley.Response;
import com.wjb.xietong.Volley.Response.ErrorListener;
import com.wjb.xietong.Volley.Response.Listener;
import com.wjb.xietong.Volley.toolbox.HttpHeaderParser;
import com.wjb.xietong.component.AppGlobal;
import com.wjb.xietong.util.LogD;

public class PostRequest extends Post<JSONObject> {

	/**
	 * Creates a new request.
	 * 
	 * @param method
	 *            the HTTP method to use
	 * @param url
	 *            URL to fetch the JSON from
	 * @param jsonRequest
	 *            A {@link JSONObject} to post with the request. Null is allowed
	 *            and indicates no parameters will be posted along with request.
	 * @param listener
	 *            Listener to receive the JSON response
	 * @param errorListener
	 *            Error listener, or null to ignore errors.
	 */
	public PostRequest(int method, String url, Map<String, String> params,
			Listener<JSONObject> listener, ErrorListener errorListener) {
		super(method, url, params, listener, errorListener);
	}

	/**
	 * Constructor which defaults to <code>GET</code> if
	 * <code>jsonRequest</code> is <code>null</code>, <code>POST</code>
	 * otherwise.
	 * 
	 * @see #JsonObjectRequest(int, String, JSONObject, Listener, ErrorListener)
	 */
	public PostRequest(String url, Map<String, String> params,
			Listener<JSONObject> listener, ErrorListener errorListener) {
		this(Method.POST, url, params, listener, errorListener);
	}

	@Override
	protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
		try {
			String sessionId = HttpHeaderParser.parseSessionId(response.headers);
			if (null != sessionId) {
				if(!sessionId.equals(AppGlobal.getInstance().getJSESSIONID())){
					LogD.output("SessionId:" + sessionId);
					AppGlobal.getInstance().setJSESSIONID(sessionId);
				}
			}
			String jsonString = new String(response.data,
					HttpHeaderParser.parseCharset(response.headers));
			return Response.success(new JSONObject(jsonString),
					HttpHeaderParser.parseCacheHeaders(response));
		} catch (UnsupportedEncodingException e) {
			return Response.error(new ParseError(e));
		} catch (JSONException je) {
			return Response.error(new ParseError(je));
		}
	}

	@Override
	public Map<String, String> getHeaders() throws AuthFailureError {
		if(null != AppGlobal.getInstance().getJSESSIONID()){
			 HashMap<String, String> headers = new HashMap<String, String>();  
	         headers.put("cookie", AppGlobal.getInstance().getJSESSIONID());
	         return headers;  
		}
		return super.getHeaders();
	}

}